package sk.pitonak.mhd;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class U {
	public static final boolean DEBUG = true;
	
	private static HttpClient mHttpClient = new DefaultHttpClient();

	public static int[] getCurrentTimeAndDate() {
		int[] date = new int[5];
		Calendar calendar = Calendar.getInstance();

		date[0] = calendar.get(Calendar.HOUR_OF_DAY);
		date[1] = calendar.get(Calendar.MINUTE);

		date[2] = calendar.get(Calendar.YEAR);
		date[3] = calendar.get(Calendar.MONTH);
		date[4] = calendar.get(Calendar.DAY_OF_MONTH);
		
		return date;
	}
	
	public static String getTimeString(int hour, int minute) {
		return String.format("%02d:%02d", hour, minute);
	}
	
	public static String getDateString(int day, int month, int year) {
		return String.format("%d.%d.%d", day, month + 1, year);
	}

	public static Thread performOnBackgroundThread(Runnable runnable) {
		Thread thread = new Thread(runnable);
		thread.start();
		return thread;
	}

	public static HttpEntity getUrlContent(String url) throws Exception {
		// TODO: specific exceptions
		// Log.i(Constants.TAG, "Fetching url: " + url);

		HttpGet get = new HttpGet(url);
		HttpResponse httpResponse = mHttpClient.execute(get);

		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if(statusCode != HttpStatus.SC_OK) {
			throw new Exception("Bad HTTP status code: " + statusCode);
		}

		return httpResponse.getEntity();
	}

	public static HttpEntity post(String url, List<NameValuePair> data) throws Exception {
		// TODO: specific exceptions
		// Log.i(Constants.TAG, "Posting to url: " + url);

		HttpPost post = new HttpPost(url);
		post.setEntity(new UrlEncodedFormEntity(data));
		HttpResponse httpResponse = mHttpClient.execute(post);

		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if(statusCode != HttpStatus.SC_OK) {
			throw new Exception("Bad HTTP status code: " + statusCode);
		}

		return httpResponse.getEntity();
	}

	public static String getStringFromUrl(String url) throws Exception {
		HttpEntity entity = getUrlContent(url);
		return EntityUtils.toString(entity);
	}

	public static Bitmap getImageFromUrl(String url) throws Exception {
		HttpEntity entity = getUrlContent(url);
		return BitmapFactory.decodeStream(entity.getContent());
	}

	public static byte[] getBytesFromUrl(String url) throws Exception {
		HttpEntity entity = getUrlContent(url);
		return EntityUtils.toByteArray(entity);
	}

	public static ArrayList<Result> getOnlineResults(String from, String to, String time, String date) throws Exception {
		String[] keys = new String[] { "?z1x=", "&z2x=", "&cas=", "&datum=" };
		String[] values = new String[] { from, to, time, date };
		
		StringBuilder builder = new StringBuilder();
		builder.append("http://imhd.zoznam.sk/ba/planovac-cesty-vyhladanie-spojenia.html");
		for(int i = 0; i < keys.length; ++i) {
			builder.append(keys[i]);
			builder.append(URLEncoder.encode(values[i]));
		}
		
		String url = builder.toString();
		String response = getStringFromUrl(url);
		
		Document document = Jsoup.parse(response);
		Elements tables = document.select("table[width=600]");
		ArrayList<Result> results = new ArrayList<Result>(tables.size());
		
		Log.i("", String.format("got %d tables", tables.size()));
		
		int i = 0;
		for(Element table : tables) {
			results.add(i, new OnlineResult(table));
			++i;
		}
		
		return results;
	}
	
	// TODO: remove
	public static ArrayList<Result> getDummyResults(Context context) {
        try {
            InputStream is = context.getAssets().open("dummy_result.txt");
            int size = is.available();
            
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            
            String text = new String(buffer);
    		
    		Document document = Jsoup.parse(text);
    		Elements tables = document.select("table[width=600]");
    		ArrayList<Result> results = new ArrayList<Result>(tables.size());
    		
    		Log.i("", String.format("got %d tables", tables.size()));
    		
    		int i = 0;
    		for(Element table : tables) {
    			results.add(i, new OnlineResult(table));
    			++i;
    		}
    		
    		return results;
            
        } catch (IOException e) {
        	e.printStackTrace();
        }
		return null;
	}
}
